const express = require("express");
const db = require("./db");
var { expressjwt: jwt } = require("express-jwt");
const _ = require("lodash");
const dayjs = require("dayjs");
const uuid = require("uuid")
const { CARD_RECORD_EXIST, SUCCESS } = require('../code.ts');
const { default: axios } = require("axios");


const router = express.Router();
let secret = "weislingpai"; //token令牌
// 计算距离
function calculateDistance(lat1, lon1, lat2, lon2) {
  const radius = 6371 * 1000; // 地球半径（单位：米）
  const dLat = deg2rad(lat2 - lat1);
  const dLon = deg2rad(lon2 - lon1);
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(deg2rad(lat1)) *
    Math.cos(deg2rad(lat2)) *
    Math.sin(dLon / 2) *
    Math.sin(dLon / 2);
  const arcLength = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

  const distance = radius * arcLength; // 距离（单位：米）
  return distance;
}
// 将角度转换为弧度
const deg2rad = (deg) => {
  return deg * (Math.PI / 180);
};

// 同步的查询语句
async function awaitSql(q) {
  const data = await new Promise((resolve, reject) => {
    db.query(q, function (err, data) {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
  return data;
}

// 登录
router.post("/login", async (req, res) => {
  let username = req.body.username;
  let password = req.body.password;

  if (username != 'null') {
    const q = `SELECT id,account,avatar,tel,name,openid  FROM student WHERE account = ?`;
    db.query(q, [username], function (err, data) {
      console.log(data);
      let AccessToken = jwt({
        secret: secret,
        expiresIn: "1h",
        algorithms: ["HS256"],
      });
      let RefreshToken = jwt({
        secret: secret,
        expiresIn: "72h",
        algorithms: ["HS256"],
      });
      if (data) {
        console.log(data,'data');
        if (data[0]?.password === password) {
          res.send({
            code: 200,
            data,
            msg: "登录成功",
            AccessToken,
            RefreshToken,
            id: data[0].id,
          });
        } else {
          res.send({
            code: 201,
            msg: "密码错误",
          });
        }
      } else {
        res.send({
          code: 403,
          msg: "用户名错误",
        });
      }
    })
  } else {
    res.send({
      code: 404,
      msg: "用户名不能为空"
    })
  }
});

// 修改用户信息
router.post('/setUser', (req, res) => {
  let body = req.body;
  console.log(body,'body');
  let keys = Object.keys(body);
  let ens = []
  keys.forEach((item) => {
    if (item != 'id') {
      ens.push(`${item} = '${body[item]}'`)
    }
  })
  q = `UPDATE student
SET ${ens.join(',')}
WHERE id = '${body.id}';`
  db.query(q, function (err, data) {
    if (err) {
      res.send({
        code: 300,
        err
      })
    } else {
      db.query(`SELECT * from student WHERE id = '${body.id}'`, (err, data) => {
        res.send({
          code: 200,
          data,
          message:'修改成功'
        })
      })
    }
  })
})
// 注册
router.post("/register", (req, res) => {
  let body = req.body;
  console.log(body,"register");
  body.id = uuid.v4()
  body.createdAt = new Date()
  if(body.name==undefined){
    body.name = body.account
  }
  let keys = Object.keys(body).join(",");
  let values = [];
  Object.values(body).forEach((item) => {
    values.push('"' + item + '"');
  });
  values = values.join(",");
  console.log(keys, 'keys');
  console.log(values, 'values');
  const q = `INSERT INTO student ( ${keys} )
  VALUES( ${values} ); `;
  console.log(q);
  db.query(q, function (err, cData) {
    console.log(cData, 'cData');
    if (err) {
      res.send({
        code: 400,
        error: err,
      });
    } else {
      res.send({
        code: 200,
        // data,
      });
    }
  });
});
// 获取商品分类列表
router.get("/productTypeList", (req, res) => {
  const q = `SELECT * FROM course_type `;
  db.query(q, function (err, data) {
    if (err) {
      res.send({
        code: 400,
        error: err,
      });
    } else {
      res.send({
        code: 200,
        data,
      });
    }
  });
});
/*router.get("/productList", async (req, res) => {
  let type = req.query.type || null;
  let schema = req.query.schema || null;
  let lat = req.query.latitude
  let lon = req.query.longitude
  console.log(type, schema);

  let schemaList = []
  let q = `SELECT * FROM course `
  // if (type !== null) {
  //   if (type != "all") {
  //     let sc = await awaitSql(`SELECT * FROM course_type WHERE name = '${type}'`)
  //     console.log('sc:', sc);
  //     schemaList.push(`typeId = ${sc[0].id}`)
  //   }
  // }
  if (schema !== null) {
    schemaList.push(`name LIKE '%${schema}%'`);
  }
  if (schemaList.length > 0) {
    q += ` WHERE `;
    q += schemaList.join(" OR ");
  }
  console.log(q);
  db.query(q, function (err, data) {
    //   data.map(item => {
    //     let oid = item.orgId;
    //     let obj = getOrganizationName(oid);
    //     item.orgId = obj;
    //     return item;
    //   })
    if (err) {
      res.send({
        code: 400,
        error: err,
      });
    } else {
      let promises = [];
      data.forEach(async (item) => {
        promises.push(
          new Promise((resolve, reject) => {
            orgDate = db.query(
              `SELECT id,name,longitude,latitude FROM organization WHERE id = '${item.orgId}' `,
              (err, data) => {
                if (err) {
                  reject(err);
                } else {
                  resolve(data);
                }
              }
            );
          })
        );
      });
      Promise.all(promises)
        .then((values) => {
          values.forEach((item, index) => {
            data[index].org = {
              id: item[0].id,
              name: item[0].name,
              distance: calculateDistance(
                lat,
                lon,
                item[0].latitude,
                item[0].longitude
              ),
            };
          });
        })
        .finally(() => {
          // 冒泡排序
          // data.sort((a, b) => {
          //   return a.org.distance - b.org.distance;
          // });
          res.send({
            code: 200,
            data,
          });
        });
    }
  });
});*/

// 获取商品列表
router.get("/productList", async (req, res) => {
  let type = req.query.type || null;
  let schema = req.query.schema || null;
  let lat = req.query.latitude;
  let lon = req.query.longitude;
  console.log(lat, lon);
  let schemaList = [];
  let q = `SELECT * FROM product`;
  if (type !== null) {
    if (type != "all") {
      let sc = await awaitSql("SELECT * FROM course_type WHERE `key` = '" + type + "'")
      console.log('sc:', sc);
      schemaList.push(`type = '${sc[0].title}' OR type = '${sc[0].key}'`)
    }
  }
  if (schema !== null) {
    schemaList.push(`name LIKE '%${schema}%'`);
  }
  if (schemaList.length > 0) {
    q += ` WHERE `;
    q += schemaList.join(" OR ");
  }
  console.log(q);
  db.query(q, function (err, data) {
    //   data.map(item => {
    //     let oid = item.orgId;
    //     let obj = getOrganizationName(oid);
    //     item.orgId = obj;
    //     return item;
    //   })
    if (err) {
      res.send({
        code: 400,
        error: err,
      });
    } else {
      let promises = [];
      data.forEach(async (item) => {
        promises.push(
          new Promise((resolve, reject) => {
            orgDate = db.query(
              `SELECT id,name,longitude,latitude FROM organization WHERE id = '${item.orgId}' `,
              (err, data) => {
                if (err) {
                  reject(err);
                } else {
                  resolve(data);
                }
              }
            );
          })
        );
      });
      Promise.all(promises)
        .then((values) => {
          values.forEach((item, index) => {
            data[index].org = {
              id: item[0]?.id,
              name: item[0].name,
              distance: calculateDistance(
                lat,
                lon,
                item[0].latitude,
                item[0].longitude
              ),
            };
          });
        })
        .finally(() => {
          // 冒泡排序
          data.sort((a, b) => {
            return a.org.distance - b.org.distance;
          });
          res.send({
            code: 200,
            data,
          })
        })
    }
  })
})

// 获取课程详情
router.get('/courseDetaile', (req, res) => {
  let id = req.query.id || null
  console.log(id, 'id--------------------------------');
  if (id === null) {
    res.send({
      code: 300,
      msg: "id不能为空",
    });
  } else {
    let sql = `select product.*, course.reserveInfo,course.refundInfo,course.otherInfo,organization.logo from product,organization,course where product.orgId=organization.id and organization.id=course.orgId and product.id=?`;
    db.query(sql, [id], function (err, result) {
      if (result) {
        res.send({ code: 200, data: result, msg: "获取成功" });
      } else {
        res.send({ code: 500, msg: "获取失败" });
      }
    });
  }
});

// 获取门店
router.get("/product", (req, res) => {
  let q = `SELECT * FROM product;`;
  db.query(q, function (err, data) {
    if (err) {
      res.send({
        code: 400,
        error: err,
      });
    } else {
      res.send({
        code: 200,
        data,
      });
    }
  });
});
// 获取门店详情
router.get("/organizationDetaile", (req, res) => {
  let id = req.query.id || null;
  if (id === null) {
    res.send({
      code: 300,
      msg: "id不能为空",
    });
  } else {
    let q = `SELECT * FROM organization WHERE id = '${id}';`;
    let frontImgs = `SELECT url FROM org_image WHERE orgIdForFrontId = '${id}';`;
    let roomImgs = `SELECT url FROM org_image WHERE orgIdForRoomId = '${id}';`;
    db.query(q, function (err, data) {
      if (err) {
        res.send({
          code: 400,
          error: err,
        });
      } else {
        fronts = db.query(frontImgs, function (err, front) {
          rooms = db.query(roomImgs, function (err, room) {
            res.send({
              code: 200,
              data: { front, room, data },
            });
          });
        });
      }
    });
  }
});

// 预约我的消费卡
router.get("/consumption", (req, res) => {
  let q = `
  SELECT c.*, t.*
  FROM course c
  JOIN course_type t ON c.orgId = t.id;  `;
  db.query(q, function (err, data) {
    console.log(err, data);
    if (err) {
      res.send({
        code: 400,
        error: err,
      });
    } else {
      res.send({
        code: 200,
        data,
      });
    }
  })
})

// 获取我的预约课程
router.get('/reservation', (req, res) => {

})

// 预约我的课程表
router.get('/myCourses', (req, res) => {

})

// 判断当前课程时段时间已经被约过了
router.get('/isHadSubscribe', (req, res) => {

})

router.get("/list", (req, res) => {
  let id = req.query.id || null;
  var sql = `select id from student where id = '${id}'`;
  db.query(sql, function (err, result) {
    //连接数据库 传入sql语句 回调函数得到结果
    try {
      console.log(result);
      res.send({ data: result }); //查询结果响应给请求方
    } catch (err) {
      console.log("查询失败");
    }
  });
});

//  预约课程列表
router.get("/getReservationList", (req, res) => {
  //获取登录用户对应的可预约的课程列表
  let studentId = req.query.id;
  // console.log(studentId);
  let sql = `select product.*,orders.*,organization.name from product,orders,organization where orders.productId=product.id and product.orgId=organization.id;`;
  db.query(sql, [studentId], function (err, result) {
    if (result.length) {
      result.map(item=>{
        item['flag']=false
      })
      console.log(result);
      res.send({ code: 200, data: result, msg: "获取成功" });
    } else {
      res.send({ code: 500, msg: "获取失败" });
    }
  });
});

// 预约课程消费卡展示
router.get("/getCardList", (req, res) => {
  let productId = req.query.id;
  let sql = `select card.* from product_card,card where product_card.cardId=card.id and product_card.productId=?`;
  db.query(sql, [productId], function (err, data) {
    if (data.length) {
      res.send({ code: 200, msg: "获取成功", data });
    } else {
      res.send({ code: 500, msg: "获取失败" });
    }
  });
});

// 课程可预约的时间
router.get("/getCourseTime", (req, res) => {
  let productId = req.query.id;
  let sql =
    "select course.reducibleTime from product_card,card,course where product_card.cardId=card.id and card.courseId=course.id and product_card.productId=?";
  db.query(sql, [productId], function (err, data) {
    if (data.length) {
      res.send({ code: 200, msg: "获取成功", data: data[0] });
    } else {
      res.send({ code: 500, msg: "获取失败" });
    }
  });
});


// // 微信授权
router.get('/wxlogin', (req, res) => {
  let userId = req.query.id
  let url = req.query.url
  // url = url.split('=')[1]
  // const APPID = process.env.WXPAY_APPID;
  const APPID = 'wx171385412597a59e';
  // const REDIRECT_URI = process.env.REDIRECT_URI;
  const REDIRECT_URI = 'http://www.coderzsc.top/nest/wxCode';
  // const REDIRECT_URI = 'http://357h3r0792.picp.vip/wxCode';
  const STATE = `${userId}@${encodeURIComponent(url)}`;
  // https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd5008d880794b7ae&redirect_uri=http://84132u8p48.yicp.fun/wxCode&response_type=code&scope=snsapi_base&state=11111#wechat_redirect
  const redirectUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=snsapi_base&state=${STATE}#wechat_redirect`
  res.send({
    code: 200,
    path:redirectUrl
  })
  // res.redirect(redirectUrl);
  // redirectUrl
})
router.get('/wxCode', async (req, res) => {
  console.log('wxCode-------------------');
  let code = req.query.code
  let state = req.query.state
  console.log('code', code);
  console.log('state', state);
  const [userId, url] = state.split('@')
  // const APPID = process.env.WXPAY_APPID;
  const APPID = 'wx171385412597a59e';
  // const SECRET = process.env.SECRET;
  const SECRET = '808bf2396a6f2bfd9486450a13040794';

  const response = await axios.get(
    `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${APPID}&secret=${SECRET}
    &code=${code}&grant_type=authorization_code`
  )
  // 还少一步
  console.log(response);
  const { openid } = response.data;
  console.log(openid, 'openid');
  // 存储openid
  // res.redirect(decodeURIComponent(url) + '?openid=' + openid);
  res.send({
    code: 200,
    message: '111111'
  })
})

// cardRecord 个人消费卡表
// 获取当前学员有效的消费卡
router.get('/findValidCards', (req, res) => {
  const studentId = req.query.studentId;
  const SQLSentence = `SELECT * FROM cardRecord WHERE studentId = ${studentId}`;

  db.query(SQLSentence, (err, res) => {
    if (err) {
      res.send({
        code: 400,
        error: err,
      });
    } else {
      const data = [];
      res.forEach((item) => {
        // 是否过期
        if (dayjs().isBefore(item.endTime)) {
          // 如果当前是次卡的话，我们需要判断是否还有剩余次数
          if (!(item.card.type === CardType.TIME && item.residueTime === 0)) {
            data.push(item);
          }
        }
      });
      res.send({
        code: 200,
        data,
      });
    }
  })

})

// 获取当前学员可以约的课程
router.get('/getCanSubscribeCourses', (req, res) => {
  const userId = req.query.studentId;
  console.log(userId, 'userId');
  // 1 获取当前学员有效的消费卡
  // 使用上面的获取当前学员有效的消费卡的接口
  const SQLSentence = `SELECT * FROM card-record WHERE studentId = ${userId}`;
  db.query(SQLSentence, (err, resData) => {
    if (err) {
      console.log('111111111')
      res.send({
        code: 400,
        error: err,
      });
    } else {
      console.log('222222222')
      const cards = [];
      resData.forEach((item) => {
        // 是否过期
        if (dayjs().isBefore(item.endTime)) {
          // 如果当前是次卡的话，我们需要判断是否还有剩余次数
          if (!(item.card.type === CardType.TIME && item.residueTime === 0)) {
            cards.push(item);
          }
        }
      });

      if (!cards || cards.length === 0) {
        res.send({
          code: CARD_RECORD_EXIST,
          message: '没有可用的消费卡，快去购买吧',
        });
      }
      // 2 获取消费卡可以约的课
      const courses = cards.map((item) => item.course);
      // 3 去除重复的课程
      const cs = _.uniqBy(courses, 'id');
      // 4 对课程做分组，按照门店
      const orgObj = {
        'dsds': {
          name: '',
          course: [
            ...course
          ]
        }
      };
      for (let i = 0; i < cs.length; i++) {
        const c = cs[i];
        if (orgObj[c.org.id]) {
          orgObj[c.org.id].courses.push(c);
        } else {
          orgObj[c.org.id] = {
            ...c.org,
            courses: [c],
          };
        }
      }
      const orgs = Object.values(orgObj);

      res.send({
        code: SUCCESS,
        message: '获取成功',
        data: orgs,
        page: {
          total: orgs.length,
        }
      })
    }
  })
})

// 获取未来有效的，7天内的课程表
router.get('/findValidSchedulesForNext7Days', (req, res) => {
  // courseId
  // schoolDay: Between( //未来7天
  //   dayjs().endOf().toDate(),
  //   dayjs().add(7,'day).endOf('day).toDate()
  // )
  // order: schoolDay:ASC   startTime:ASC

  // 返回值：entities,count

  let SQL = `SELECT * FROM schedule WHERE course=${courseId}`;

  db.query(SQL, (err, data) => {
    if (err) {
      res.send({
        code: 500,
        err
      })
    } else {
      res.send({
        code: 200,
        data
      })
    }
  })



})

// 获取到某一个课程的近七天的课程表
router.get('/getSchedulesByCourse', (req, res) => {
  // 先调用上面的接口
  const [entities, count] = [];

  res.send({
    code: SUCCESS,
    message: '获取成功',
    data: entities,
    page: {
      total: count,
    }
  })

})

// 获取所有课程表
router.get('/getSchedules', (req, res) => {
  // 参数一 today  参数二 orgId

})

// 获取某人可用的消费卡
router.get('/findUseCards', (req, res) => {
  // 参数 studentID   courseID
  // 查询card-Record表    管理card
  // 查询到的值 cards count
  // 循环判断card是否过期   newCards = []
  // 最后返回newCards, count

  const [cards] = [];
  const newCards = [];
  cards.forEach((card) => {
    if (!dayjs().isAfter(card.endTime)) {
      // 时长卡 没有过期
      if (card.card.type === CardType.DURATION) {
        // 没有过期，且是时长卡
        newCards.push(card);
      }
      if (card.card.type === CardType.TIME && card.residueTime > 0) {
        // 没有过期，且是次卡，同时还有次数
        newCards.push(card);
      }
    }
  })
  return [newCards, newCards.length];
});

// 获取当前学员在某个课程上可以用的消费卡
router.get('/getUseCardRecordsByCourse', (req, res) => {
  // 参数   userId 学员ID  courseId 课程ID
  // 查询表 cardRecord

  // 调用上面 获取某人可用的消费卡 findUseCards

  const [cards, total] = [];

  res.send({
    code: SUCCESS,
    message: '获取成功',
    data: cards,
    page: {
      total,
    }
  });
});

// 预约课程页面接口 -----------------------------------------

// 确定预约课程接口
router.get('/subscribeCourse', (req, res) => {
  // 参数一 scheduleID string
  // 参数二 cardID string
  // 参数三 studentID string

  // 第一步：校验
  const myCard = [];
  if (!myCard) {
    res.send({
      code: CARD_NOT_EXIST,
      message: '消费卡不存在'
    })
  }

  // 判断是否过期
  if (dayjs().isAfter(myCard.endTime)) {
    res.send({
      code: CARD_EXPIRED,
      message: '消费卡已经过期'
    })
  }

  // 判断消费卡是否耗尽
  if (myCard.card.type === CardType.TIME && myCard.residueTime === 0) {
    res.send({
      code: CARD_DEPLETE,
      message: '消费卡次数已经耗尽了'
    })
  }

  // 根据scheduleID查询schedule表
  const schedule = [];
  // 校验是否存在该课程
  if (!schedule) {
    res.send({
      code: SCHEDULE_NOT_EXIST,
      message: '当前课程表不存在'
    });
  }

  // 第二步：创建预约记录
  // 引入schedule-record表
  // create创建
  const scheduleRecordId = {
    subscribeTime: '1',
    student: {
      id: '1'
    },
    schedule: {
      id: '1'
    },
    cardRecord: {
      id: '1'
    },
    course: {
      id: schedule.course.id
    },
    org: {
      id: schedule.org.id
    }
  };

  // 判断是否能拿到，生成数据后的ID
  if (!scheduleRecordId) {
    res.send({
      code: SUBSCRIBE_FAIL,
      message: '预约失败'
    });
  }


  // 第三步 销卡
  if (myCard.card.type === CardType.TIME) {
    // card-record表 update
    const resData = cardRecord.update(cardId, {
      residueTime: myCard.residueTime - 1,
    });
    if (resData) {
      res.send({
        code: SUCCESS,
        message: '预约成功',
      });
    } else {
      // 预约失败后，根据ID删除该条数据
      // scheduleRecord.deleteById(scheduleRecordId)
      res.send({
        code: SUBSCRIBE_FAIL,
        message: '预约失败'
      });
    }
  }
  res.send({
    code: SUCCESS,
    message: '预约成功',
  });
})

// 微信授权，购买成功后，给消费者添加消费卡
router.get('/addCardForStudent', (req, res) => {
  // 参数 studentId:string  cardIds:string[]
  let studentId = req.q.cards
  let cardIds = req.query.cardIds;

  for (let i = 0; i < cardIds.length; i++) {
    const cardId = cardIds[i];
    // 获取当前cardId获取到对应的card
    // const card = 
  }
})


// 我的课程页面的接口 ----------------------------------------

// 获取我的课程表记录
router.get('/getScheduleRecords', (req, res) => {
  // 查询表 schedule  course   org  schedule.teacher
  const Id = req.query.Id;
  // 查询该用户studentId所有的课程记录表scheduleRecord
  const getScheduleRecord = (Id) => {
    return new Promise(resolve => {
      // 获取scheduleRecord SQL 
      // 这里如何根据ID查询，需要加引号包裹，否则查询不到数据！！！！！！！！！！！！！！
      const srSql = `SELECT * FROM scheduleRecord WHERE studentId = '${Id}'`;
      db.query(srSql, function (srErr, srData) {
        if (srErr) return console.log(srErr.message);
        resolve(srData)
      })
    })
  }

  // 根据课程记录中scheduleId查询课程表schedule
  const getSchedule = (scheduleId) => { 
    return new Promise(resolve => {
      const sSql = `SELECT * FROM schedule WHERE id = '${scheduleId}'`;
      db.query(sSql, function (scheduleErr, scheduleData) {
        if (scheduleErr) return console.log(scheduleErr.message);
        scheduleData.time = scheduleData.startTime + ' - ' + dayjs(scheduleData.endTime).format('HH:mm:ss');
        resolve(scheduleData)
      })
    })
  }

  // 根据课程记录中的courseId查询课程表course
  const getCourse = (courseId) => { 
    return new Promise(resolve => {
      const courseSql = `SELECT * FROM course WHERE id = '${courseId}'`;
      db.query(courseSql, function (courseErr, courseData) {
        if (courseErr) return console.log(courseErr.message);
        resolve(courseData)
      })
    })
  }

  // 根据课程记录中的orgId查询门店表organization
  const getOrganization = (orgId) => { 
    return new Promise(resolve => {
      const organizationSql = `SELECT * FROM organization WHERE id = '${orgId}'`;
      db.query(organizationSql, function (organizationErr, organizationData) {
        if (organizationErr) return console.log(organizationErr.message);
        resolve(organizationData)
      })
    })
  }

  async function getStudentScheduleRecord() {
    const studentSchedules = await getScheduleRecord(Id);
    let data = [];

    for (let i = 0; i < studentSchedules.length; i++) { 
      const schedule = await getSchedule(studentSchedules[i].scheduleId);
      const course = await getCourse(studentSchedules[i].courseId);
      const organization = await getOrganization(studentSchedules[i].orgId);

      schedule[0].time = schedule[0].startTime + ' - ' + dayjs(schedule[0].endTime).format('HH:mm:ss');

      data.push({
        id: studentSchedules[i].id,
        time: schedule[0].time,
        status: studentSchedules[i].status,
        courseImg: {
          coverUrl: course[0].coverUrl
        },
        schedule: {
          schoolDay: schedule[0].schoolDay,
          startTime: dayjs(schedule[0].startTime).format('HH:mm:ss'),
          endTime: dayjs(schedule[0].endTime).format('HH:mm:ss'),
          teacher: {
            name: '王小龙'
          }
        },
        org: {
          id: organization[0].id,
          logo: organization[0].logo
        },
        course: {
          name: course[0].name,
        }
      })
    }
    res.send({
      code: 200,
      message:'成功',
      data: data
    })
  }
  getStudentScheduleRecord()

   // 获取对应course SQL
  //  const courseSql = `SELECT * FROM course WHERE id = '${srData[i].courseId}'`;
  //  db.query(courseSql, function (courseErr, courseData) {
  //    console.log('courseData--------------222222222222----------------------');
  //    if (courseData && courseData.length >= 1) {
  //      // 获取对于 schedule SQL
  //      const scheduleSql = `SELECT schoolDay,startTime,endTime FROM schedule WHERE id = '${srData[i].scheduleId}'`;
  //      db.query(scheduleSql, function (scheduleErr, scheduleData) {
  //        if (scheduleData && courseData.length >= 1) {
  //          scheduleData.time = scheduleData.startTime + ' - ' + dayjs(scheduleData.endTime).format('HH:mm:ss');
  //          // 获取对应的organtation SQL
  //          const organtationSql = `SELECT id,logo FROM organization WHERE id = '${srData[i].orgId}'`
  //          db.query(organtationSql, function (orgErr, orgData) {
  //            // console.log('orgData--------------44444444444----------------------');
  //            if (orgData && orgData.length >= 1) {
  //              data.push({
  //                id: srData[i].id,
  //                time: scheduleData[i].time,
  //                status: srData[i].status,
  //                couseImg: {
  //                  coverUrl: courseData[i].coverUrl
  //                },
  //                schedule: {
  //                  schoolDay: scheduleData[i].schoolDay,
  //                  startTime: dayjs(scheduleData[0].startTime).format('HH:mm:ss'),
  //                  endTime: dayjs(scheduleData[0].endTime).format('HH:mm:ss'),
  //                  teacher: {
  //                    name: '王小龙'
  //                  }
  //                },
  //                org: {
  //                  id: orgData[0].id,
  //                  logo: orgData[0].logo
  //                },
  //                course: {
  //                  name: courseData[i].name,
  //                }
  //              })
  //            } else {
  //              res.send({
  //                code: 500,
  //                message: 'orgErr' + orgErr
  //              })
  //            }
  //          })
  //        } else {
  //          res.send({
  //            code: 500,
  //            message: 'scheduleErr' + scheduleErr
  //          })
  //        }
  //      })
  //    } else {
  //      res.send({
  //        code: 500,
  //        message: 'courseErr' + courseErr
  //      })
  //    }
  //  })
})

// 修改我的课程表记录的状态
router.post('/updateScheduleRecordStatus', (req, res) => {
  console.log('1111111111111111111111111111');
  let id = req.query.id;
  console.log(id, 'id');
  const Sql = `UPDATE scheduleRecord SET status = 'CANCEL' WHERE id = '${id}'`;
  db.query(Sql, function (err, data) {
    if (err) {
      res.send({
        code: 500,
        message: err
      })
    } else {
      res.send({
        code: 200,
        message: '取消成功'
      })
    }
  })
})


// 我的消费卡页面的接口 ----------------------------------------

// 获取用户对应的消费卡
router.get('/getMyCard', (req, res) => {
  let studentId = req.query.id
  console.log(studentId, 'studentId');
  let sql = "select product.*,organization.name as orgName,card.*,orders.* from orders,product,organization,product_card,card where orders.productId=product.id and product.orgId=organization.id and product.id=product_card.productId and product_card.cardId=card.id and orders.studentId=?"
  db.query(sql, [studentId], function (err, result) {
    if (result.length) {
      res.send({ code: 200, msg: '获取成功', data: result })
    } else {
      res.send({ code: 500, msg: '获取失败' })
    }
  })
})





module.exports = router;

